package cn.mujiankeji.mbrowser.工具

import android.content.Context
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.booleanPreferencesKey
import androidx.datastore.preferences.core.doublePreferencesKey
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.emptyPreferences
import androidx.datastore.preferences.core.floatPreferencesKey
import androidx.datastore.preferences.core.intPreferencesKey
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.map
import java.io.IOException

abstract class 配置助手(private val context: Context,
                        filenma : String = "settings") {

    private val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = filenma)

    @Suppress("UNCHECKED_CAST")
    fun <T>读取(key : String, def : T) : Flow<T> {
        return context.dataStore.data
            .catch { exception ->
                if (exception is IOException) {
                    emit(emptyPreferences())
                } else {
                    throw exception
                }
            }
            .map { preferences ->
                when(def) {
                    is String -> (preferences[stringPreferencesKey(key)] ?: def) as T
                    is Int -> (preferences[intPreferencesKey(key)] ?: def) as T
                    is Double -> (preferences[doublePreferencesKey(key)] ?: def) as T
                    is Float -> (preferences[floatPreferencesKey(key)] ?: def) as T
                    is Boolean -> (preferences[booleanPreferencesKey(key)] ?: def) as T
                    else -> throw Exception("不兼容的类型 -> ${def}")
                }
            }
    }



    suspend fun 设置(key : String, value : Any) {
        context.dataStore.edit { preferences ->
            when(value) {
                is String -> preferences[stringPreferencesKey(key)] = value
                is Int -> preferences[intPreferencesKey(key)] = value
                is Double -> preferences[doublePreferencesKey(key)] = value
                is Float -> preferences[floatPreferencesKey(key)] = value
                is Boolean -> preferences[booleanPreferencesKey(key)] = value
                else -> throw Exception("不兼容的类型 -> ${value::class.java.simpleName}")
            }
        }
    }

   /* *//**
     * 清除指定配置项
     * @param key 配置项键名
     *//*
    suspend fun 清除配置项(key: String) {
        context.dataStore.edit { preferences ->
            preferences.keys.find { it.name == key }?.let { preferences.remove(it) }
        }
    }*/

    /**
     * 清除所有配置项
     */
    suspend fun 清除所有配置() {
        context.dataStore.edit { preferences ->
            preferences.clear()
        }
    }
}